package com.yoshino.leetcode.oneHundred.seventeenth;

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        if (arr.length == 0 || k == 0)  {
            return new int[1];
        }
        Queue<Integer> queue = new PriorityQueue<>((v1, v2) -> v2.compareTo(v1));
        for (int num : arr) {
            if (queue.size() < k) {
                queue.add(num);
            } else {
                if (queue.peek() > num) {
                    queue.poll();
                    queue.add(num);
                }
            }
        }
        int[] res = new int[k];
        int ind = 0;
        for (int num : queue) {
            res[ind++] = num;
        }
        return res;
    }

    public int[] getLeastNumbers2(int[] arr, int k) {
        Arrays.sort(arr);
        return Arrays.copyOfRange(arr, 0, k);
    }
}